import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components"

/**
 * 系统设置页面
 * 配置3条RS485总线串口参数
 * 
 * 布局优化（1024×768分辨率）：
 * - 可用区域：794px宽 × 738px高（1024-200侧栏-30顶栏 × 768-30顶栏）
 * - 标题栏：50px
 * - 状态栏：45px  
 * - ScrollView：551px（可滚动）
 *   - 3个BusConfigCard：120px × 3 = 360px
 *   - 卡片间距：10px × 2 = 20px
 *   - 波特率配置：55px
 *   - 内部间距：10px × 3 = 30px
 *   - 总计：465px（留86px余量）
 * - 底部操作：60px
 * - 主间距：8px × 4 = 32px
 */
Item {
    id: root

    // 本地状态
    property var availablePorts: []
    property bool systemRunning: false

    // 配置数据
    property string bus1Port: ""
    property string bus2Port: ""
    property string bus3Port: ""
    property int baudRate: 115200

    // 连接状态
    property bool bus1Opened: false
    property bool bus2Opened: false
    property bool bus3Opened: false

    // 初始化定时器
    Timer {
        id: initTimer
        interval: 100
        running: true
        repeat: false
        onTriggered: {
            loadConfiguration()
            scanPorts()
        }
    }

    // 状态更新定时器
    Timer {
        id: statusTimer
        interval: 1000
        running: true
        repeat: true
        onTriggered: {
            updateStatus()
        }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 8

        // 页面标题（压缩到50px）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 50
            color: "white"
            radius: 6

            RowLayout {
                anchors.fill: parent
                anchors.margins: 12
                spacing: 10

                Text {
                    text: "⚙️ 系统设置"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#2c3e50"
                }

                Rectangle {
                    width: 1
                    height: 20
                    color: "#d0d0d0"
                }

                Text {
                    text: "配置3条RS485总线串口参数，连接120块PM2220电表"
                    font.pixelSize: 11
                    color: "#7f8c8d"
                }

                Item { Layout.fillWidth: true }
            }
        }

        // 系统状态栏（压缩到45px）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 45
            color: systemRunning ? "#27ae60" : "#95a5a6"
            radius: 6

            RowLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 12

                Rectangle {
                    width: 10
                    height: 10
                    radius: 5
                    color: "white"
                    
                    SequentialAnimation on opacity {
                        running: systemRunning
                        loops: Animation.Infinite
                        NumberAnimation { to: 0.3; duration: 1000 }
                        NumberAnimation { to: 1.0; duration: 1000 }
                    }
                }

                Text {
                    id: statusText
                    text: systemRunning ? "系统运行中" : "系统已停止"
                    font.pixelSize: 14
                    font.bold: true
                    color: "white"
                    Layout.fillWidth: true
                }

                Text {
                    id: detailStatusText
                    text: settingsManager ? settingsManager.getSystemStatus() : ""
                    font.pixelSize: 11
                    color: "white"
                }
            }
        }

        // 串口配置区域（最大化填充剩余空间）
        ScrollView {
            Layout.fillWidth: true
            Layout.fillHeight: true
            clip: true
            contentWidth: availableWidth

            ColumnLayout {
                width: parent.width
                spacing: 10

                // 配电室A配置卡片
                BusConfigCard {
                    id: bus1Card
                    Layout.fillWidth: true
                    
                    busId: 1
                    busName: "配电室A"
                    busIcon: "🏢"
                    slaveRange: "1-40"
                    selectedPort: root.bus1Port
                    portOpened: root.bus1Opened
                    availablePorts: root.availablePorts
                    currentBaudRate: root.baudRate

                    onPortSelected: function(port) {
                        root.bus1Port = port
                    }

                    onOpenPortClicked: function(port) {
                        openPort(port, root.baudRate)
                    }

                    onClosePortClicked: function(port) {
                        closePort(port)
                    }
                }

                // 配电室B配置卡片
                BusConfigCard {
                    id: bus2Card
                    Layout.fillWidth: true
                    
                    busId: 2
                    busName: "配电室B"
                    busIcon: "🏭"
                    slaveRange: "41-80"
                    selectedPort: root.bus2Port
                    portOpened: root.bus2Opened
                    availablePorts: root.availablePorts
                    currentBaudRate: root.baudRate

                    onPortSelected: function(port) {
                        root.bus2Port = port
                    }

                    onOpenPortClicked: function(port) {
                        openPort(port, root.baudRate)
                    }

                    onClosePortClicked: function(port) {
                        closePort(port)
                    }
                }

                // 配电室C配置卡片
                BusConfigCard {
                    id: bus3Card
                    Layout.fillWidth: true
                    
                    busId: 3
                    busName: "配电室C"
                    busIcon: "🏗"
                    slaveRange: "81-120"
                    selectedPort: root.bus3Port
                    portOpened: root.bus3Opened
                    availablePorts: root.availablePorts
                    currentBaudRate: root.baudRate

                    onPortSelected: function(port) {
                        root.bus3Port = port
                    }

                    onOpenPortClicked: function(port) {
                        openPort(port, root.baudRate)
                    }

                    onClosePortClicked: function(port) {
                        closePort(port)
                    }
                }

                // 波特率配置（压缩到55px）
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 55
                    color: "white"
                    radius: 6

                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 12
                        spacing: 12

                        Text {
                            text: "⚡ 波特率"
                            font.pixelSize: 13
                            font.bold: true
                            color: "#2c3e50"
                        }

                        ComboBox {
                            id: baudRateCombo
                            Layout.preferredWidth: 130
                            implicitHeight: 30
                            font.pixelSize: 11
                            model: [9600, 19200, 38400, 57600, 115200]
                            currentIndex: 4 // 默认115200

                            onActivated: {
                                root.baudRate = model[currentIndex]
                            }
                        }

                        Text {
                            text: "bps"
                            font.pixelSize: 11
                            color: "#7f8c8d"
                        }

                        Item { Layout.fillWidth: true }
                    }
                }
            }
        }

        // 底部操作区（压缩到60px）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 60
            color: "white"
            radius: 6

            RowLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 8

                Button {
                    text: "🔍 扫描串口"
                    font.pixelSize: 11
                    implicitHeight: 32
                    Layout.preferredWidth: 100
                    onClicked: scanPorts()
                }

                Button {
                    text: "💾 保存配置"
                    font.pixelSize: 11
                    implicitHeight: 32
                    Layout.preferredWidth: 100
                    onClicked: saveConfiguration()
                }

                Rectangle {
                    width: 1
                    height: 35
                    color: "#bdc3c7"
                }

                Button {
                    text: systemRunning ? "⏹ 停止系统" : "▶ 启动系统"
                    font.pixelSize: 11
                    font.bold: true
                    implicitHeight: 32
                    Layout.preferredWidth: 100
                    
                    background: Rectangle {
                        color: systemRunning ? "#e74c3c" : "#27ae60"
                        radius: 4
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        font: parent.font
                        color: "white"
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }

                    onClicked: {
                        if (systemRunning) {
                            stopSystem()
                        } else {
                            startSystem()
                        }
                    }
                }

                Button {
                    text: "🔄 重启系统"
                    font.pixelSize: 11
                    implicitHeight: 32
                    Layout.preferredWidth: 100
                    enabled: systemRunning
                    onClicked: restartSystem()
                }

                Item { Layout.fillWidth: true }

                Text {
                    text: "已打开串口: " + (portManager ? portManager.openedPortCount : 0) + " / 3"
                    font.pixelSize: 11
                    color: "#7f8c8d"
                }
            }
        }
    }

    // 监听串口管理器信号
    Connections {
        target: portManager

        function onPortOpened(portName) {
            console.log("串口已打开:", portName)
            updatePortStatus()
            showMessage("成功", "串口 " + portName + " 已打开", "success")
        }

        function onPortClosed(portName) {
            console.log("串口已关闭:", portName)
            updatePortStatus()
            showMessage("提示", "串口 " + portName + " 已关闭", "info")
        }

        function onPortError(portName, errorString) {
            console.log("串口错误:", portName, errorString)
            showMessage("错误", "串口 " + portName + " 错误: " + errorString, "error")
        }
    }

    // 监听设置管理器信号
    Connections {
        target: settingsManager

        function onConfigurationApplied() {
            console.log("配置已应用")
            showMessage("成功", "配置已保存并应用", "success")
        }

        function onConfigurationFailed(errorMessage) {
            console.log("配置失败:", errorMessage)
            showMessage("错误", errorMessage, "error")
        }

        function onSystemStatusChanged(status) {
            console.log("系统状态:", status)
            detailStatusText.text = status
        }

        function onIsPollingChanged() {
            systemRunning = settingsManager.isPolling
        }
    }

    // 监听设备管理器信号
    Connections {
        target: deviceManager

        function onTopologyDiscoveryProgress(current, total) {
            detailStatusText.text = "正在扫描设备 " + current + "/" + total
        }

        function onTopologyDiscoveryCompleted(totalFound) {
            showMessage("完成", "拓扑识别完成，发现 " + totalFound + " 块在线电表", "success")
        }
    }

    // JavaScript 函数

    // 加载配置
    function loadConfiguration() {
        if (!settingsManager) return

        var config = settingsManager.loadCurrentConfig()
        
        root.bus1Port = config.bus1Port || ""
        root.bus2Port = config.bus2Port || ""
        root.bus3Port = config.bus3Port || ""
        root.baudRate = config.baudRate || 115200

        root.bus1Opened = config.bus1Opened || false
        root.bus2Opened = config.bus2Opened || false
        root.bus3Opened = config.bus3Opened || false

        // 更新波特率下拉框
        var rates = [9600, 19200, 38400, 57600, 115200]
        baudRateCombo.currentIndex = rates.indexOf(root.baudRate)

        console.log("配置已加载:", JSON.stringify(config))
    }

    // 扫描串口
    function scanPorts() {
        if (!portManager) return

        root.availablePorts = portManager.scanAvailablePorts()
        console.log("扫描到串口:", root.availablePorts.join(", "))
        
        if (root.availablePorts.length === 0) {
            showMessage("提示", "未发现可用串口", "warning")
        } else {
            showMessage("成功", "发现 " + root.availablePorts.length + " 个串口", "success")
        }
    }

    // 打开串口
    function openPort(portName, baudRate) {
        if (!portManager || !portName) return

        console.log("打开串口:", portName, "波特率:", baudRate)
        portManager.openPort(portName, baudRate)
    }

    // 关闭串口
    function closePort(portName) {
        if (!portManager || !portName) return

        console.log("关闭串口:", portName)
        portManager.closePort(portName)
    }

    // 保存配置
    function saveConfiguration() {
        if (!settingsManager) return

        // 验证配置
        var error = settingsManager.validateConfiguration(root.bus1Port, root.bus2Port, root.bus3Port)
        if (error) {
            showMessage("错误", error, "error")
            return
        }

        // 应用配置
        console.log("保存配置 - Bus1:", root.bus1Port, "Bus2:", root.bus2Port, "Bus3:", root.bus3Port, "波特率:", root.baudRate)
        settingsManager.applyConfiguration(root.bus1Port, root.bus2Port, root.bus3Port, root.baudRate)
    }

    // 启动系统
    function startSystem() {
        if (!settingsManager) return

        console.log("启动系统")
        var success = settingsManager.startSystem()
        
        if (!success) {
            showMessage("失败", "系统启动失败，请检查配置", "error")
        }
    }

    // 停止系统
    function stopSystem() {
        if (!settingsManager) return

        console.log("停止系统")
        settingsManager.stopSystem()
        systemRunning = false
    }

    // 重启系统
    function restartSystem() {
        if (!settingsManager) return

        console.log("重启系统")
        settingsManager.restartSystem()
    }

    // 更新状态
    function updateStatus() {
        updatePortStatus()
        
        if (settingsManager) {
            systemRunning = settingsManager.isPolling
        }
    }

    // 更新串口状态
    function updatePortStatus() {
        if (!portManager) return

        root.bus1Opened = portManager.isPortOpen(root.bus1Port)
        root.bus2Opened = portManager.isPortOpen(root.bus2Port)
        root.bus3Opened = portManager.isPortOpen(root.bus3Port)
    }

    // 显示消息
    function showMessage(title, message, type) {
        console.log("[" + type + "]", title + ":", message)
        // TODO: 可以添加 Toast 提示或 Dialog 对话框
    }

    // 组件加载完成
    Component.onCompleted: {
        console.log("SettingsPage loaded")
    }
}

